﻿using System;
using System.Windows.Forms;
using System.Web.Security;

namespace AspUserManager
{
	public partial class EditUserDialog : Form
	{
		public MembershipUser user;

		public EditUserDialog(MembershipUser user)
		{
			this.user = user;
			InitializeComponent();
		}

		public MembershipUser User
		{ get { return user; } }

		private void EditUserDialog_Load(object sender, EventArgs e)
		{
			// Fill the roles list
			foreach (string role in Roles.GetAllRoles())
				listRoles.Items.Add(role);

			if (user != null) {
				// push data to form
				txtUser.Text = user.UserName;
				txtUser.ReadOnly = true;
				txtCreated.Text = user.CreationDate.ToString();
				txtLastLogin.Text = user.LastLoginDate.ToString();
				txtEmail.Text = user.Email;
				txtComment.Text = user.Comment;

				// show different fields for edit
				txtPassword.Visible = false;
				txtConfirm.Visible = false;
				lblPassword.Visible = false;
				lblConfirm.Visible = false;
				lblCreated.Visible = true;
				txtCreated.Visible = true;
				lblLastLogin.Visible = true;
				txtLastLogin.Visible = true;

				// check the selected roles
				foreach (string role in Roles.GetRolesForUser(user.UserName)) {
					int idx = listRoles.Items.IndexOf(role);
					listRoles.SetItemChecked(idx, true);
				}
			}
 		}

		private void butOK_Click(object sender, EventArgs e)
		{
			if (!CreateUpdateUser())
				DialogResult = DialogResult.None;
		}

		private bool CreateUpdateUser()
		{
			try {
				if (user == null)
					user = Membership.CreateUser(txtUser.Text, txtPassword.Text);
				user.Comment = txtComment.Text;
				user.Email = txtEmail.Text;
				Membership.UpdateUser(user);
				
				// add/remove this users roles 
				string[] currentRoles = Roles.GetRolesForUser(user.UserName);
				for (int i = 0; i < listRoles.Items.Count; ++i) {
					string role = (string)listRoles.Items[i];
					if (listRoles.GetItemChecked(i)) {
						if (!Contains (currentRoles, role))
							Roles.AddUserToRole(user.UserName, role);
					} else {
						if (Contains (currentRoles, role))
							Roles.RemoveUserFromRole(user.UserName, role);
					}
				}
				
			} catch (Exception ex) {
				MessageBox.Show("The user could not be created/updated for the following reason:\n\n" +
					ex.Message, Application.ProductName);
				return false;
			}
			return true;
		}

		private static bool Contains (string[] roles, string role)
		{
			for (int i = 0; i < roles.Length; ++i) {
				if (roles[i] == role)
					return true;
			}
			return false;
		}
	}
}
